﻿namespace Manhua2.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Windows.Graphics.Imaging;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Media.Imaging;

    public class GIF : Panel
    {
        private static DependencyProperty _IndexProperty =
            DependencyProperty.Register("Index", typeof(double), typeof(GIF), 
                new PropertyMetadata(0, IndexChangedCallback));

        public static DependencyProperty IndexProperty
        {
            get { return GIF._IndexProperty; }
        }
        
        private List<BitmapSource> bmps = new List<BitmapSource>();

        public GIF()
        {
        }

        public Image Image { get; set; }

        public double Index 
        {
            get 
            {
                return (double)this.GetValue(IndexProperty);
            }
            set
            {
                this.SetValue(IndexProperty, value);
            }
        }

        public async Task ReadGIF(IRandomAccessStream file)
        {
            var decoder = await BitmapDecoder.CreateAsync(file);
            uint count = decoder.FrameCount;

            for (uint i = 0; i < count; i++)
            {
                var frame = await decoder.GetFrameAsync(i);
                var provider = await frame.GetPixelDataAsync();
                byte[] buffer = provider.DetachPixelData();
                var dest = new InMemoryRandomAccessStream();

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, dest);
                encoder.SetPixelData(frame.BitmapPixelFormat, BitmapAlphaMode.Premultiplied, frame.PixelWidth,
                    frame.PixelHeight, frame.DpiX, frame.DpiY, buffer);

                await encoder.FlushAsync();
                dest.Seek(0);
                BitmapImage bmp = new BitmapImage();
                bmp.SetSource(dest);

                this.bmps.Add(bmp);
            }
        }

        private static void IndexChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            GIF gif = (GIF)d;
            if (gif.Image != null)
            {
                int index = (int)double.Parse(e.NewValue.ToString());
                if (index < gif.bmps.Count && index >= 0)
                {
                    gif.Image.Source = gif.bmps[index];
                }
            }
        }
    }
}
